package fr.umlv.m2.jee.ldap.web.authentification;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.webflow.action.MultiAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

@SuppressWarnings("serial")
@Component
@Scope("session")
@Deprecated
public class ConnexionActions extends MultiAction implements Serializable {
    private String authenticated;

    public Event findName(RequestContext context) {
        String username = null;
        context.getFlowScope().put("username", username);
        return success();
    }

    public String doLogin() throws IOException, ServletException {
        authenticated = "FAILURE";
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        System.out.println("LA ------> information " + context.getSessionMap().get("userName"));

        context.getSessionMap().remove("userName");
        context.getSessionMap().remove("viewExpired");

        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/j_spring_security_check");

        dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());

        FacesContext.getCurrentInstance().responseComplete();

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        context.getSessionMap().put("auth", auth);

        System.out.println("information sur auth " + auth);

        if (auth != null) {
            authenticated = "SUCCESS";
        }

        String destURL = (String) context.getSessionMap().get("destURL");
        if (destURL != null && !"".equals(destURL)) {
            context.getSessionMap().remove("destURL");
            ((HttpServletResponse) context.getResponse()).sendRedirect(destURL);
        }

        System.out.println("IIIIIIICCCCIIII ? " + authenticated);

        logger.debug("Authentification " + authenticated);
        return null;
    }

    public String getAuthenticated() {
        return authenticated;
    }

    public void setAuthenticate(String authenticated) {
        this.authenticated = authenticated;
    }
}
